package com.work.straighttalk.model;


import android.net.Uri;
import android.os.Handler;
import android.widget.Toast;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.work.straighttalk.StraightTalkPlayer;
import com.work.straighttalk.app.StraightTalk;
import com.work.straighttalk.bean.StraightTalkMessage;
import com.work.straighttalk.model.i.ChatMI;
import com.work.straighttalk.model.i.SeekBarProgressListener;
import com.work.straighttalk.presenter.i.OnIMSendListener;
import com.work.straighttalk.presenter.i.OnLoadFinishedListener;
import com.work.straighttalk.presenter.i.SeekBarMaxListener;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 用于发送消息
 * Created by dllo on 16/3/4.
 */
public class ChatMImpl implements ChatMI {
    private EaseVoiceRecorder easeVoiceRecorder;
    private EMConversation conversation;
    private StraightTalkPlayer player;
    private Handler handler;
    private List<StraightTalkMessage> messages;
    private EMMessageSender sender;

    /**
     * 构造方法 中将toUser :id 传入
     * 初始化 工具
     *
     * @param id
     */
    public ChatMImpl(String id) {
        //信息发送者的初始化
        this.sender = new EMMessageSender(id);
        this.easeVoiceRecorder = new EaseVoiceRecorder();
        //------用于conversation 的加载
        this.conversation = EMClient.getInstance().chatManager().getConversation(id, EMConversation.EMConversationType.Chat, true);
        if (null != this.conversation.getLastMessage()) {
            String startMsgID = this.conversation.getLastMessage().getMsgId();
            this.conversation.loadMoreMsgFromDB(startMsgID, 19);
        }
        //--------------------
        //播放器的初始化
        player = new StraightTalkPlayer();
        handler = new Handler();
        //信息容器初始化
        messages = new ArrayList<>();
    }

    /**
     * emMessage 通过此方法生成 并且它的状态为create
     *
     * @param content
     */
    @Override
    public void sendTextMessage(String content, OnIMSendListener listener) {
        sender.sendTextMessage(content);
        refreshMessage(listener);
    }

    private void refreshMessage(final OnIMSendListener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                getSTMessageList();
                listener.afterSend(messages);
            }
        }).start();
    }

    /**
     *
     */
    private void getSTMessageList() {
        messages.clear();
        List<EMMessage> emMessages = conversation.getAllMessages();
        for (Iterator iterator = emMessages.iterator(); iterator.hasNext(); ) {
            EMMessage emMessage = (EMMessage) iterator.next();
            StraightTalkMessage message = new StraightTalkMessage();
            message.setEmMessage(emMessage);
            messages.add(message);
        }
    }

    @Override
    public void queryMessage(final OnLoadFinishedListener<List<StraightTalkMessage>> listener) {
//获取此会话的所有消息
        new Thread(new Runnable() {
            @Override
            public void run() {
                getSTMessageList();
                listener.onLoadSuccess(messages);
            }
        }).start();
//sdk初始化加载的聊天记录为20条，到顶时需要去db里获取更多
//获取startMsgId之前的pagesize条消息，此方法获取的messages sdk会自动存入到此会话中，app中无需再次把获取到的messages添加到会话中
//        List<EMMessage> messages = conversation.loadMoreMsgFromDB(startMsgId, pagesize);
    }


    @Override
    public void removeMessage() {

    }

    @Override
    public void playVoice(final StraightTalkMessage message, final SeekBarProgressListener listener, SeekBarMaxListener maxListener, StraightTalkPlayer.PlayerCallBack playerCallBack) {
        player.playVoice(message);
//        Toast.makeText(StraightTalk.applicationContext, ""+player.getDuration(), Toast.LENGTH_SHORT).show();
        maxListener.proofread(message.getEmMessage().getMsgId(), player.getDuration());
        player.setPlayerCallBack(playerCallBack);
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (player.isPlaying()) {
                    listener.returnProgress(message.getEmMessage().getMsgId(), player.getCurrentPosition());
                    handler.postDelayed(this, 100);
                }
            }
        });

    }

    @Override
    public void pauseVoice() {
        player.pausePlayer();
    }


    @Override
    public void recordVoice() {
        easeVoiceRecorder.startRecording();
    }

    @Override
    public void discardVoice() {
        easeVoiceRecorder.discardRecording();
    }

    /**
     * 发送语音消息
     */
    @Override
    public void sendVoiceMessage(OnIMSendListener listener) {
        int length = easeVoiceRecorder.stopRecoding();
        String path = easeVoiceRecorder.getVoiceFilePath();
        sender.sendVoiceMessage(path, length);
        refreshMessage(listener);
    }

    /**
     * 由activity传来的seekbar progress值来控制player进度
     * player 的播放进度
     *
     * @param progress 进度值
     */
    @Override
    public void seekTo(int progress) {
        player.seekTo(progress);
    }

    /**
     * 发送图片消息 通过
     *
     * @param uri
     * @param listener
     */
    @Override
    public void sendPicByUri(Uri uri, OnIMSendListener listener) {
        //
        PicUriTransformer transformer = new PicUriTransformer(StraightTalk.applicationContext);
        String path = transformer.transPicUriToPath(uri);
        sender.sendImageMessage(path);
        refreshMessage(listener);
    }

}
